package a08_回溯算法;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

/**
 * <p>
 * a08_组合总和2复习2
 * </p>
 *
 * @author flyduck
 * @since 2025/2/17
 */
public class a08_组合总和2复习2 {

    public static void main(String[] args) {
        a08_组合总和2复习2 test = new a08_组合总和2复习2();
        List<List<Integer>> lists = test.combinationSum2(new int[]{2, 5, 2, 1, 2}, 5);
    }

    //横向去重
    //纵向不去重
    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        Arrays.sort(candidates);
        List<List<Integer>> result = new ArrayList<>();
        LinkedList<Integer> path = new LinkedList<>();
        boolean[] used = new boolean[candidates.length];
        traversal(result, path, 0, used, candidates, target, 0);
        return result;
    }

    private void traversal(List<List<Integer>> result,
                           LinkedList<Integer> path,
                           int sum,
                           boolean[] used,
                           int[] candidates,
                           int target,
                           int startIdx){
        if(sum >= target){
            if(sum == target){
                result.add(new ArrayList<>(path));
                return;
            }else {
                return;
            }
        }


        for (int i = startIdx; i < candidates.length; i++) {
            //如何横向去重，纵向不去重
            //比如2，如果前一个也是2，但是used[i-1]=false，说明是横向重复，直接跳过
            if(i >= 1 && candidates[i] == candidates[i-1] && !used[i-1]){
                continue;
            }
            path.add(candidates[i]);
            sum += candidates[i];
            used[i] = true;
            traversal(result, path,sum, used, candidates, target, i + 1);
            path.removeLast();
            sum -= candidates[i];
            used[i] = false;
        }
    }
}
